package com.example.sangong.aspect;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.example.sangong.entity.SgLog;
import com.example.sangong.kafka.KafkaSendHelper;
import com.example.sangong.myannotation.SysLog;
import com.example.sangong.myenum.DeleteFlagEnum;
import com.example.sangong.req.Req;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统日志切面
 */
@Aspect  // 使用@Aspect注解声明一个切面
@Component
@Slf4j
public class SysLogAspect {


    @Autowired
    private KafkaSendHelper kafkaSendHelper;

    @Value("${kafka.log-topic}")
    private String logTopic;

    /**
     * 这里我们使用注解的形式
     * 当然，我们也可以通过切点表达式直接指定需要拦截的package,需要拦截的class 以及 method
     * 切点表达式:   execution(...)
     * <p>
     * execution(public * *(..)) 任意的公共方法
     * execution（* set*（..）） 以set开头的所有的方法
     * execution（* com.LoggerApply.*（..））com.LoggerApply这个类里的所有的方法
     * execution（* com.annotation.*.*（..））com.annotation包下的所有的类的所有的方法
     * execution（* com.annotation..*.*（..））com.annotation包及子包下所有的类的所有的方法
     * execution(* com.annotation..*.*(String,?,Long)) com.annotation包及子包下所有的类的有三个参数，第一个参数为String类型，第二个参数为任意类型，第三个参数为Long类型的方法
     * execution(@annotation(com.lingyejun.annotation.Lingyejun))
     */
    @Pointcut("@annotation(com.example.sangong.myannotation.SysLog)")
    public void logPointCut() {
    }

    /**
     * 环绕通知 @Around  ， 当然也可以使用 @Before (前置通知)  @After (后置通知)
     *
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        Object result = point.proceed();
        long time = System.currentTimeMillis() - beginTime;
        try {
            log.info("切面的线程id:{}", Thread.currentThread().getId());
            saveLog(point, time);
        } catch (Exception e) {
            throw e;
        }
        return result;
    }

    /**
     * 保存日志
     */
    private void saveLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SgLog sgLog = new SgLog();
        sgLog.setId(IdUtil.getSnowflake().nextId());
        sgLog.setExeTime(time);
        sgLog.setThreadId(Thread.currentThread().getId());

        SysLog sysLog = method.getAnnotation(SysLog.class);
        if (sysLog != null) {
            //注解上的描述
            sgLog.setRemark(sysLog.value());
        }
        //请求的 类名、方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sgLog.setClassName(className);
        sgLog.setMethodName(methodName);
        sgLog.setCreateTime(LocalDateTime.now());
        sgLog.setDeleteFlag(DeleteFlagEnum.EFFECTIVE.getCode());

        initRequestInfo(sgLog);


        //请求的参数
        Object[] args = joinPoint.getArgs();
        try {
            List<String> list = new ArrayList<>();
            for (Object o : args) {

                list.add(JSONUtil.toJsonStr(o));
                if (!(o instanceof Req)) {
                    continue;
                }
                String seqNo = ((Req) o).getSeqNo();
                if (StrUtil.isBlank(seqNo)) {
                    continue;
                }
                sgLog.setSeqNo(seqNo);
            }
            sgLog.setParams(list.toString());
        } catch (Exception e) {
            log.error("保存日志异常了", e);

        }
        kafkaSendHelper.sendMsgAsync(logTopic, JSONUtil.toJsonStr(sgLog));

    }

    private static void initRequestInfo(SgLog sgLog) {
        //获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        sgLog.setUrl(request.getRequestURI());
        sgLog.setRequestIp(request.getRemoteAddr());
    }
}